<?php
require_once '../config/config.php';

//require_once '../libs/db.php';
//require_once '../libs/ihelper.php';

require_once('class.phpmailer.php');
require_once '../classes/user.php';

//class User {
//
//    private $name;
//    private $email;
//    private $password;
//    private $confpass;
//    private $userid;
//    private $passmd5;
//
//    public function getUsername() {
//        return $this->name;
//    }
//
//    public function setUsername($username) {
//        $this->name = $username;
//    }
//
//    public function getEmail() {
//        return $this->email;
//    }
//
//    public function setEmail($email) {
//        $this->email = $email;
//    }
//
//    public function getPassword() {
//        return $this->password;
//    }
//
//    public function setPassword($password) {
//        $this->password = $password;
//    }
//
//    public function getConfpass() {
//        return $this->confpass;
//    }
//
//    public function setConfpass($confpass) {
//        $this->confpass = $confpass;
//    }
//
//    public function setUserid($userid) {
//        $this->userid = $userid;
//    }
//
//    public function getUserid() {
//        return $this->userid;
//    }
//
//    public function getPassmd5() {
//        return $this->passmd5;
//    }
//
//    public function setPassmd5($passmd5) {
//        $this->passmd5 = $passmd5;
//    }
//
//
//}

class userManager {

    public $missing = array();
    public $errs = array();
    private $required;
    private $conn;
    private $salt = "$0ftB1ll";

    public function userManager() {
        $this->conn = DB::getInstance();
    }

    public function setRequired($req) {
        if (is_array($req)) {
            $this->required = $req;
        }
    }

    public function createUserAccount($user) {

        $valid = true;

        $valid = $this->validateInput($user);

        // save user to table
        if ($valid) {
            $valid = $this->saveUser($user);
        }
        
        if ($valid) {
            $this->sendWelcomeMail($user);
        }

        return $valid;
    }

    function validateInput($user) {

        $valid = true;

//        // create variables
//        foreach ($this->required as $key => $value) {
//            ${$value} = '';
//        }
//
//        // check all required fields in POST
//        foreach ($_POST as $key => $value) {
//            // assign to temp var and strip whitespaces if not an array
//            $temp = is_array($value) ? $value : trim($value);
//
//            // if empty and required, add to missing array
//            if (empty($temp) && in_array($key, $this->required)) {
//                $this->missing[] = $key;
//            } else {
//                ${$key} = htmlentities($temp);
//            }
//        }
//        if (empty($username)) {
//            $this->errs["username"] = "User name cannot be blank.";
//            $valid = false;
//        }
        // 
        
        if(!$user->getUsername()) {
            $this->errs["username"] = ihelper::lang("ACCOUNT_SPECIFY_NAME");
        } else {
            if(!ctype_alnum($user->getUsername())) {
                $this->errs["username"] = ihelper::lang("ACCOUNT_NAME_INVALIDCHARS");
            }
        }
        
        // check for valid email address
        if (!$user->getEmail()) {
            $this->errs["email"] = ihelper::lang("ACCOUNT_SPECIFY_EMAIL");
            $valid = false;
        } else {
            $valid = (bool) (ihelper::validate_email($user->getEmail()));
            if (!$valid) {
                $this->errs["email"] = ihelper::lang("ACCOUNT_INVALID_EMAIL");
            } else {
                // check if email already exists in database
                $stmt = "SELECT 1 " .
                        "  FROM users " .
                        " WHERE email = :email ";

                $sth = $this->conn->prepare($stmt);
                $sth->bindParam(':email', $user->getEmail(), PDO::PARAM_STR);
                $sth->execute();

                if ($sth) {
                    if ($sth->rowCount() > 0) {
                        //$this->errs["email"] = "Email already registered.";
                        $this->errs["email"] = ihelper::lang("ACCOUNT_EMAIL_IN_USE", array($user->getEmail()));
                        $valid = false;
                    }
                }
            }
        }

        if (!$user->getPassword() || !$user->getConfpass() ||
                ($user->getPassword() != $user->getConfpass())) {
            $this->errs["password"] = ihelper::lang("ACCOUNT_PASS_MISMATCH");
            $valid = false;
        }

        if (!isset($_POST["terms"])) {
            $this->errs["terms"] = ihelper::lang("ACCOUNT_LICENSE_ACCEPT");
            $valid = false;
        }

        return $valid;
    }

    function saveUser($user) {

        $valid = true;

        $stmt = "INSERT INTO users " .
                "  (email, password, master) " .
                "VALUES(:email, :password, 1) ";

        $sth = $this->conn->prepare($stmt);
        $sth->bindParam(':email', $user->getEmail(), PDO::PARAM_STR);
        $sth->bindParam(':password', $user->getPassword(), PDO::PARAM_STR);
        $sth->execute();
        if (!$sth) {
            $this->errs["register"] = "Unable to register user.";
            $valid = false;
        }
        $sth->closeCursor();

        return $valid;
    }

    function sendWelcomeMail($user) {
        //mail('kishore@ifox.in', 'New User Registration', $user->getEmail() . ' has been registered');

        $valid = true;
        $body = $user->getEmail() . " has been registered.";

        // mail settings
        $mail = new PHPMailer(); // defaults to using php "mail()"
        $mail->IsSMTP();
        $mail->Host       = "smtp.ifox.in";
        $mail->SMTPDebug  = 1;                   // for debugging information
        $mail->SMTPAuth   = true;
        $mail->SMTPSecure = "ssl";
        $mail->Port       = 465;                // Gmail's smtp port
        $mail->Username   = "support@ifox.in";
        $mail->Password   = "kishor2000";
        $mail->SetFrom('support@ifox.in', 'iFox Support');
        $mail->AddReplyTo('support@ifox.in', 'iFox Support');
        $mail->Subject    = "Using ifox smtp";
        $mail->AltBody    = "This message sent using ifox smtp";
        $mail->MsgHTML($body);

        //$mail->AddReplyTo("name@yourdomain.com", "First Last");

        $address = "kishore@ifox.in";
        $mail->AddAddress($address, "Kish");

//        $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
//
//
//        $mail->AddAttachment("images/phpmailer.gif");      // attachment
//        $mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

        if (!$mail->Send()) {
            $this->errs["mailerror"] = "Mailer Error: " . $mail->ErrorInfo;
            $valid = false;
        }

        return $valid;
    }
    
    public function verifyUserCredentials($user) {
        //$useremail = htmlentities($useremail);
        //$password = htmlentities($password);
        $valid = true;

        $stmt = "SELECT userid,active " .
                "  FROM users " .
                " WHERE email = :email " .
                "   AND password = :password";

        $sth = $this->conn->prepare($stmt);
        $sth->bindParam(':email', $user->getEmail(), PDO::PARAM_STR);
        $sth->bindParam(':password', $user->getPassword(), PDO::PARAM_STR);
        $sth->execute();
        
        if ($sth) {
            if ($sth->rowCount() == 0) {
                $this->errs["verify"] = ihelper::lang("ACCOUNT_EMAIL_OR_PASS_INVALID");
                $valid = false;
            } else {
                $result = $sth->fetch(PDO::FETCH_ASSOC);
                // users.active = 0 means account disabled
                if ($result['active'] == 0) {
                    $this->errs["verify"] = ihelper::lang("ACCOUNT_USER_DISABLED");
                    $valid = false;
                } else {
                    
                }
            }  
        }
        $sth->closeCursor();

        return $valid;
    }

    public function resetPassword($useremail) {
        $useremail = htmlentities($useremail);

        // validate email address
        $valid = ihelper::validate_email($useremail);
        if (!$valid) {
            $this->errs["email"] = "Invalid email address";
        } else {
            $stmt = "SELECT 1 " .
                    "  FROM users " .
                    " WHERE email = :email ";

            $sth = $this->conn->prepare($stmt);
            $sth->bindParam(':email', $useremail, PDO::PARAM_STR);
            $sth->execute();

            $valid = ($sth->rowCount() > 0);
            if ($valid) {
                // do password reset
            }
        }

        return $valid;
    }

}

// end: usermanager class
